package com.youlai.mybatis.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zc
 * @date 2023-03-18 22:37
 */
@Component
@Slf4j
public class MyCustomCache implements Cache, Serializable {

    private String id;
    private Map<Object, Object> cache = new ConcurrentHashMap<>();

    public MyCustomCache() {
    }

    public MyCustomCache(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        log.info("获取缓存标识:{}",id);
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        log.info("添加缓存key:{},value:{}",key,value);
        cache.put(key, value);
    }

    @Override
    public Object getObject(Object key) {
        log.info("获取缓存key:{}",key);
        return cache.get(key);
    }

    @Override
    public Object removeObject(Object key) {
        log.info("删除缓存key:{}",key);
        return cache.remove(key);
    }

    @Override
    public void clear() {
        log.info("清空缓存");
        cache.clear();
    }

    @Override
    public int getSize() {
        log.info("获取缓存数量:{}",cache.size());
        return cache.size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        log.info("拿锁");
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
        return readWriteLock;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cache);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        cache = (Map<Object, Object>) in.readObject();
    }

}

